<?php

namespace addons\shopro\listener\activity;

use addons\shopro\exception\Exception;
use addons\shopro\model\OrderItem;
use addons\shopro\model\User;
use addons\shopro\model\Goods;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\model\Activity;
use addons\shopro\model\ActivityGrouponLog;
use addons\shopro\model\Order;
use addons\shopro\model\UserWalletLog;

/**
* 成团事件
*/
class Groupon
{

    // 拼团成功
    /* 原有逻辑,屏蔽 add by lomon
    public function activityGrouponFinish(&$params) {
        $groupon = $params['groupon'];
        $goods = Goods::where('id', $groupon['goods_id'])->find();

        // 查询所有参与该团的真实用户 users & grouponLogs & grouponLeader
        extract($this->getActivityGrouponUsers($groupon));

        // 获取所有订单，判断是否需要自动发货，并且发货
        // 拿到所有订单 id 
        $orderIds = array_column($grouponLogs, 'order_id');
        // 获取该团的所有订单
        $orders = Order::where('id', 'in', $orderIds)->select();
        foreach ($orders as $order) {
            // 检测是否有需要自动发货的商品，并且发货
            $order->grouponCheckAndSend($order);
        }

        if ($users) {
            \addons\shopro\library\notify\Notify::send(
                $users, 
                new \addons\shopro\notifications\Groupon([
                    'groupon' => $groupon, 
                    'grouponLogs' => $grouponLogs, 
                    'grouponLeader' => $grouponLeader, 
                    'goods' => $goods, 
                    'event' => 'groupon_success'
                ])
            );
        }
    }
    */

    // 拼团成功
    public function activityGrouponFinish(&$params) {
        $groupon = $params['groupon'];
        $goods = Goods::where('id', $groupon['goods_id'])->find();

        // 查询所有参与该团的真实用户 users & grouponLogs & grouponLeader
        extract($this->getActivityGrouponUsers($groupon));

        // 获取所有订单，判断是否需要自动发货，并且发货
        // 拿到所有订单 id
        $orderIds = array_column($grouponLogs, 'order_id');
        // 获取该团的所有订单
        $orders = Order::where('id', 'in', $orderIds)->select();

        /*---------BEGIN-----------*/
        $userModel = new User();
        $userWallet = new UserWalletLog();

        $activity = Activity::get($groupon['activity_id']);
        $rules = $activity['rules'];
        $money_back = $rules['money_back'] ?? 0;

        //随机检测一个订单发货
        $total = count($orders);
        $random = rand(1,$total);
        $i = 1;

        foreach ($orders as $order) {
            if($i == $random){
                // 检测是否有需要自动发货的商品，并且发货
                $order->grouponCheckAndSend($order);
                // 修改 logs 为已完成
                foreach ($grouponLogs as $log){
                    if($log->order_id == $order['id']){
                        $log->status = 'finish';
                        $log->save();
                        break;
                    }
                }
            }else{
                //返回金额并且退款
                if ($order && $order['status'] > 0) {
                    // 退款，只能有一个 item
                    $item = $order['item'][0];
                    if ($item && in_array($item['refund_status'], [OrderItem::REFUND_STATUS_NOREFUND, OrderItem::REFUND_STATUS_ING])) {
                        // 未申请退款，或者退款中，直接全额退款
                        Order::startRefund($order, $order['item'][0], $order['pay_fee'], null, '拼团成功但获取失败退款');
                    }
                    // 修改 logs 为已退款
                    foreach ($grouponLogs as $log){
                        if($log->order_id == $order['id']){
                            $log->is_refund = 1;
                            $log->status = 'finish-fail';
                            $log->money_back = $money_back;
                            $log->save();
                            break;
                        }
                    }

                    if($money_back){
                        $user = clone $userModel;
                        $useradd = $user->find($order['user_id']);
                        //钱包余额
                        db('user')->where(['id'=>$useradd->id])->setInc('money',$money_back);

                        db('retail_user')->where(['uid'=>$useradd->id])->setInc('total_income',$money_back);

                        $wallet = clone $userWallet;
                        $wallet->doAdd($useradd, $money_back, "groupon_back", $order['id'], "money", 1);
                    }
                }
            }

            $i++;
        }

        if ($users) {
            \addons\shopro\library\notify\Notify::send(
                $users,
                new \addons\shopro\notifications\Groupon([
                    'groupon' => $groupon,
                    'grouponLogs' => $grouponLogs,
                    'grouponLeader' => $grouponLeader,
                    'goods' => $goods,
                    'event' => 'groupon_success'
                ])
            );
        }
    }

    
    // 拼团失败
    public function activityGrouponFail(&$params) {
        $groupon = $params['groupon'];
        $goods = Goods::where('id', $groupon['goods_id'])->find();

        // 查询所有参与该团的真实用户 users & grouponLogs & grouponLeader
        extract($this->getActivityGrouponUsers($groupon));

        if ($users) {
            \addons\shopro\library\notify\Notify::send(
                $users,
                new \addons\shopro\notifications\Groupon([
                    'groupon' => $groupon,
                    'grouponLogs' => $grouponLogs, 
                    'grouponLeader' => $grouponLeader, 
                    'goods' => $goods, 
                    'event' => 'groupon_fail'
                ])
            );
        }
    }


    // 查询所有参与该团的真实用户
    private function getActivityGrouponUsers($groupon) {
        $grouponLogs = ActivityGrouponLog::where('groupon_id', $groupon['id'])->where('is_fictitious', 0)->select();
        $user_ids = array_column($grouponLogs, 'user_id');

        // 所有用户
        $users = User::where('id', 'in', $user_ids)->select();

        // 团长
        $grouponLeader = null;
        foreach ($users as $key => $user) {
            if ($user['id'] == $groupon['user_id']) {
                $grouponLeader = $user;
                break;
            }
        }

        return compact("users", "grouponLogs", "grouponLeader");
    }
    
}
